﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using SLS.ExClassLib.Events;
/*
 * 创建新纪录时，首先根据模板查询，然后将值传入新纪录
 */
namespace LanSunERP
{

    public partial class SQLFunction
    {
        
        public DataSet SaveRecord(DataTable tableTarget, bool update = true)
        {
            DataSet setReturn = new DataSet();
            string TBName = tableTarget.TableName;
            DataRow dwQueryCond;
            DataRow rowExist = null;
            try
            {
                foreach (DataRow rowTarget in tableTarget.Rows)
                {
                    dwQueryCond = MapDataRow("", "", TBName + "QueryCond", rowTarget, null, null, true);
                    rowExist = IsExistRecord(dwQueryCond, TBName);
                    //Tracer.Verbose("SaveRecord: rowExist", rowExist);
                    //Tracer.Verbose("SaveRecord: rowTarget", rowTarget);
                    if (!rowExist.Table.TableName.EndsWith("QueryCond"))
                    {
                        dwQueryCond["UID"] = rowExist["UID"];
                        dwQueryCond[""] = rowExist[""];
                        if (update)
                        {
                            UpdateRecord(dwQueryCond, TBName);
                            rowExist.ItemArray = rowTarget.ItemArray;
                        }
                        else
                        {
                            rowTarget.ItemArray = rowExist.ItemArray;
                        }
                    }
                    else
                    {
                        InsertRecord(dwQueryCond, TBName);
                        rowExist = IsExistRecord(dwQueryCond, TBName);
                    }
                    setReturn = ImportDataTable(setReturn, rowExist);
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return setReturn;
        }
        public DataSet SaveRecord(DataSet setSave, bool update = true)
        {
            DataSet setReturn = new DataSet();
            DataSet setResult = new DataSet();
            string TBName;
            try
            {
                foreach (DataTable tableTemp in setSave.Tables)
                {
                    TBName = tableTemp.TableName;
                    setResult = new DataSet();
                    setResult = SaveRecord(tableTemp, update);
                    setReturn.Merge(setResult);
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            //Tracer.Verbose("SaveRecord: setReturn", setReturn);
            return setReturn;
        }


        public virtual DataRow PrepareQueryCond(string QueryType, string TForeignKey,
            string TableQueryCond, DataRow dwSource, Queue ForeignKeyList, Queue PrimaryKeyList)
        {
            //DataRow dwTarget = MapDataRow(QueryType, TForeignKey, TableQueryCond, dwSource, ForeignKeyList, PrimaryKeyList, true);
            DataRow dwTarget = MapDataRow(QueryType, TForeignKey, TableQueryCond, dwSource, null, null, true);

            string GTKEY = "";
            if (dwSource.Table.Columns.Contains("GTKEY")
             && !dwSource.Table.TableName.Contains("GTPREDef"))
            {
                GTKEY = dwSource["GTKEY"].ToString().Trim();
                if (GTKEY == "")
                {
                    if (dwTarget.Table.Columns.Contains("KREAL"))
                    {
                        dwTarget["KREAL"] = dwSource.Table.TableName;
                    }
                }
            }
            //Tracer.Verbose("PrepareQueryCond", dwTarget);
            return dwTarget;
        }
        
        private DataSet InsertGoodsMasterKeyRelation(DataRow dwGDKEY)
        {
            #region Variable
            DataRow dwQueryCond;
            string TargetTable;
            string SubStatus;
            TargetTable = dwGDKEY.Table.TableName.Replace("QueryCond", "");
            SubStatus = dwGDKEY["SUBSTATUS"].ToString().Trim();
            DataSet setRequest = new DataSet();
            DataSet setReturn = new DataSet();
            DataSet setTemp1 = new DataSet();
            DataSet setTemp2 = new DataSet();
            DataSet setTemp3 = new DataSet();
            Queue QFroeignKey = new Queue();
            Queue QSourceKey = new Queue();
            Dictionary<string, object> dicReturn;
            DataTable tableGTPREDefRelation = null;
            DataTable tableExpand = null;
            DataSet setExpandSource = new DataSet();
            DataTable tableGoodsMasterKeyRelation = null;
            DataRow rowGTPREDefRelation = null, rowGTPREDefRelationQueryCond = null;
            DataRow rowGoodsMasterKeyRelation = null, rowGoodsMasterKeyRelationQueryCond = null;
            List<string> ListSForeignKey;
            string TBName;
            DataRow rowTemp = null;
            int SGroupLevel;
            DataRow rowReference = null;
            DataTable tableGroupBase = null;
            DataRow rowGroupBase = null;
            bool flgFind = false;
            DataRow[] rowsTemp;
            string expression;
            string sTargetTable, SMultiKey, MSM, MGDKEY, MKREAL, MKeyDefType, MGTPRE, MGTKEY,
                SSM, SGDKEY, SKREAL, SKeyDefType, SGTPRE, SGTKEY,
                SM, KREAL, KeyDefType, GTPRE, GTKEY, GDKEY,
                SForeignKey;
            #endregion

            #region Validate the Record
            if (TargetTable == "GoodsMasterKey"
                || TargetTable == "GTPREDef"
                || TargetTable == "GoodsMasterProperty"
                || TargetTable == "SysKeyData"
                 || TargetTable == "GoodsMasterKeyRelation"
                 || TargetTable == "GTPREDefRelation"
                 || TargetTable == "GoodsMasterAssemblePoint"
                 || TargetTable == "GoodsTypeAssemblePointDef"
                 )
                return setReturn;
            #endregion
            try
            {
                #region Get CreateByQueryCurrent GoodsMasterKeyRelation
                dwQueryCond = setQueryCond.GoodsMasterKeyRelationQueryCond.NewRow();
                dwQueryCond["QUERYTYPE"] = "CreateByQuery";
                dwQueryCond["CONDTYPE"] = "IX_GoodsMasterKeyRelation_Key";
                dwQueryCond["SM"] = dwGDKEY["SM"];
                dwQueryCond["KREAL"] = TargetTable;
                dwQueryCond["KEYDEFTYPE"] = dwGDKEY["KEYDEFTYPE"];
                dwQueryCond["GTPRE"] = dwGDKEY["GTPRE"];
                dwQueryCond["GTKEY"] = dwGDKEY["GTKEY"];
                dwQueryCond["GDKEY"] = dwGDKEY["GDKEY"];
                dwQueryCond["MGDKEY"] = dwGDKEY["GDKEY"];
                #endregion
                setTemp1 = new DataSet();
                setTemp1 = QueryAndCreateTable(dwQueryCond, true, false);
                tableGoodsMasterKeyRelation = setTemp1.Tables["GoodsMasterKeyRelation"];
                rowGoodsMasterKeyRelation = tableGoodsMasterKeyRelation.Rows[0];
                tableGTPREDefRelation = setTemp1.Tables["GTPREDefRelation"];
                rowGTPREDefRelation = tableGTPREDefRelation.Rows[0];
                #region  if (SMultiKey == "YES")
                if (tableGTPREDefRelation != null)
                {
                    SMultiKey = rowGTPREDefRelation["SMULTIKEY"].ToString().Trim().ToUpper();
                    if (SMultiKey == "YES")
                    {
                        #region GDKEY
                        GDKEY = dwGDKEY["GDKEY"].ToString().Trim();
                        #endregion

                        #region MGDKEY
                        MSM = rowGoodsMasterKeyRelation["SM"].ToString().Trim().ToUpper();
                        MKREAL = rowGoodsMasterKeyRelation["MKREAL"].ToString().Trim().ToUpper();
                        MKeyDefType = rowGoodsMasterKeyRelation["MKEYDEFTYPE"].ToString().Trim().ToUpper();
                        MGTPRE = rowGoodsMasterKeyRelation["MGTPRE"].ToString().Trim().ToUpper();
                        MGTKEY = rowGoodsMasterKeyRelation["MGTKEY"].ToString().Trim().ToUpper();
                        MGDKEY = rowGoodsMasterKeyRelation["MGDKEY"].ToString().Trim().ToUpper();
                        #endregion

                        #region SGDKEY
                        SForeignKey = rowGTPREDefRelation["SFOREIGNKEY"].ToString().Trim().ToUpper();
                        SGroupLevel = System.Convert.ToInt16(rowGTPREDefRelation["SGROUPLEVEL"].ToString().Trim().ToUpper());
                        SSM = rowGoodsMasterKeyRelation["SM"].ToString().Trim().ToUpper();
                        SKREAL = rowGoodsMasterKeyRelation["SKREAL"].ToString().Trim().ToUpper();
                        SKeyDefType = rowGoodsMasterKeyRelation["SKEYDEFTYPE"].ToString().Trim().ToUpper();
                        SGTPRE = rowGoodsMasterKeyRelation["SGTPRE"].ToString().Trim().ToUpper();
                        SGTKEY = rowGoodsMasterKeyRelation["SGTKEY"].ToString().Trim().ToUpper();
                        //                        ListSForeignKey = GetForeingKeyList(MKREAL, SForeignKey);
                        //dwForeignKeyLists = TBForeignKeyList.Select("TBNAME='" + MKREAL + "' and TForeignKey='" + SForeignKey + "'");
                        ListSForeignKey = GetSourceForeingKey(SKREAL, SForeignKey);
                        dwForeignKeyLists = TBForeignKeyList.Select("TBNAME='" + SKREAL + "' and FOREIGNKEY='" + SForeignKey + "'");
                        if (dwForeignKeyLists.Count() > 0)
                        {
                            sTargetTable = dwForeignKeyLists[0]["TARGETTABLE"].ToString().Trim();
                        }
                        else
                        {
                            return null;
                        }
                        #endregion
                        #region Find the group basetable in order to expore
                        TBName = sTargetTable;
                        QFroeignKey = new Queue();
                        QSourceKey = new Queue();
                        for (int i = 0; i < ListSForeignKey.Count(); i++)
                        {
                            string stemp = ListSForeignKey[i].ToString();
                            QFroeignKey.Enqueue(stemp);
                            QSourceKey.Enqueue(stemp);
                        }

                        rowReference = setReference.Tables[MKREAL].Rows[0];
                        rowTemp = MapDataRow("QueryOnly", SForeignKey,
                            TBName + "QueryCond", rowReference, QFroeignKey, QSourceKey, false);
                        setTemp1 = new DataSet();
                        setTemp1 = QueryAndCreateTable(rowTemp);
                        tableGroupBase = setTemp1.Tables[TBName];
                        rowGroupBase = tableGroupBase.Rows[0];

                        SM = rowGroupBase["SM"].ToString().Trim().ToUpper();
                        KREAL = rowGroupBase.Table.TableName;
                        KeyDefType = rowGroupBase["KEYDEFTYPE"].ToString().Trim().ToUpper();
                        GTPRE = rowGroupBase["GTPRE"].ToString().Trim().ToUpper();
                        GTKEY = rowGroupBase["GTKEY"].ToString().Trim().ToUpper();
                        GDKEY = rowGroupBase["GDKEY"].ToString().Trim().ToUpper();

                        string LastTable;
                        flgFind = false;
                        dicReturn = LoadDataTableByConditions(TBName, "", SM, KeyDefType, GTPRE, GTKEY, GDKEY);
                        setTemp2 = (DataSet)dicReturn["setReturn"];
                        DataTable dtTempX = null;
                        LastTable = (string)dicReturn["LastTable"];
                        if (LastTable == SKREAL)
                        {
                            flgFind = true;
                            tableExpand = setTemp2.Tables[LastTable];
                        }
                        else
                        {
                            dtTempX = setTemp2.Tables[LastTable];
                        }
                        while (!flgFind)
                        {
                            foreach (DataRow dwTemp in dtTempX.Rows)
                            {
                                TBName = LastTable;
                                KeyDefType = dwTemp["KEYDEFTYPE"].ToString().Trim().ToUpper();
                                GTPRE = dwTemp["GTPRE"].ToString().Trim().ToUpper();
                                GTKEY = dwTemp["GTKEY"].ToString().Trim().ToUpper();
                                GDKEY = dwTemp["GDKEY"].ToString().Trim().ToUpper();
                                dicReturn = LoadDataTableByConditions(TBName, "", SM, KeyDefType, GTPRE, GTKEY, GDKEY);
                                setTemp3 = (DataSet)dicReturn["setReturn"];
                                LastTable = (string)dicReturn["LastTable"];
                                if (LastTable.ToUpper() == SKREAL.ToUpper())
                                {
                                    flgFind = true;
                                    setExpandSource = ImportDataTable(setExpandSource, setTemp3.Tables[LastTable]);
                                }
                            }
                            if (!flgFind)
                            {
                                dtTempX = setReturn.Tables[LastTable];
                            }
                        }
                        #endregion
                        tableExpand = setExpandSource.Tables[SKREAL];
                    }
                }
                #endregion

                #region Expand GoodsMasterKeyRelation
                DataSet setExpand = new DataSet();
                DataRow rowRelationExpand = null;
                DataRow rowMasterExpand = null;
                if (tableExpand != null)
                {
                    int PostionI = 0;
                    foreach (DataRow dwTemp in tableExpand.Rows)
                    {
                        rowRelationExpand = setGlobal.GoodsMasterKeyRelation.NewRow();
                        rowRelationExpand.ItemArray = rowGoodsMasterKeyRelation.ItemArray;
                        rowRelationExpand["SGDKEY"] = dwTemp["GDKEY"];
                        rowRelationExpand["LINE"] = 0;
                        rowRelationExpand["GDKEY"] = rowRelationExpand["MGDKEY"].ToString().Trim() + "." + rowRelationExpand["SGDKEY"].ToString().Trim();
                        rowMasterExpand = setGlobal.Tables[TargetTable].NewRow();
                        rowMasterExpand.ItemArray = dwGDKEY.ItemArray;
                        rowMasterExpand["GDKEY"] = rowRelationExpand["GDKEY"];
                        PostionI = System.Convert.ToInt16(dwTemp["POS"].ToString());
                        rowRelationExpand = Build(rowRelationExpand, PostionI);
                        rowMasterExpand = Build(rowMasterExpand, PostionI);
                        setExpand = ImportDataTable(setExpand, rowMasterExpand);
                        setExpand = ImportDataTable(setExpand, rowRelationExpand);
                    }
                }
                #endregion
                foreach (DataTable dtTmp in setExpand.Tables)
                {
                    setReturn = ImportDataTable(setReturn, dtTmp);
                }
                //此时，判断GoodsTyepKeyDefRelation是否是一对多模板
                //如果成立，则产生多条GoodsMasterKeyRelation和dwGDKEY 
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return setReturn;
        }
        private DataSet MultiSlaveKeyGoodsMasterKeyRelation(DataRow dwGDKEY)
        {
            #region Variable
            DataRow dwQueryCond;
            string TargetTable;
            string SubStatus;
            TargetTable = dwGDKEY.Table.TableName.Replace("QueryCond", "");
            SubStatus = dwGDKEY["SUBSTATUS"].ToString().Trim();
            DataSet setRequest = new DataSet();
            DataSet setReturn = new DataSet();
            DataSet setTemp1 = new DataSet();
            DataSet setTemp2 = new DataSet();
            DataSet setTemp3 = new DataSet();
            Queue QFroeignKey = new Queue();
            Queue QSourceKey = new Queue();
            Dictionary<string, object> dicReturn;
            DataTable tableGTPREDefRelation = null;
            DataTable tableExpand = null;
            DataSet setExpandSource = new DataSet();
            DataTable tableGoodsMasterKeyRelation = null;
            DataRow rowGTPREDefRelation = null, rowGTPREDefRelationQueryCond = null;
            DataRow rowGoodsMasterKeyRelation = null, rowGoodsMasterKeyRelationQueryCond = null;
            List<string> ListSForeignKey = new List<string>();
            List<string> listKeyCome = null;
            List<string> listKeyGo = null;
            List<string> listKeyGDKEY = null;
            string TBName;
            DataRow rowTemp = null;
            int SGroupLevel;
            DataRow rowReference = null;
            DataTable tableGroupBase = null;
            DataRow rowGroupBase = null;
            bool flgFind = false;
            DataRow[] rowsTemp;
            string expression;
            string sTargetTable, SMultiKey, MSM, MGDKEY, MKREAL, MKeyDefType, MGTPRE, MGTKEY,
              SSM, SGDKEY, SKREAL, SKeyDefType, SGTPRE, SGTKEY,
              SM, KREAL, KeyDefType, GTPRE, GTKEY, GDKEY,
              SForeignKey;
            #endregion

            #region Validate the Record
            if (TargetTable == "GoodsMasterKey"
                || TargetTable == "GTPREDef"
                || TargetTable == "GoodsMasterProperty"
                || TargetTable == "SysKeyData"
                 || TargetTable == "GoodsMasterKeyRelation"
                 || TargetTable == "GoodsMasterAssemblePoint"
                 || TargetTable == "GTPREDefRelation"
                 )
            {
                setReturn = ImportDataTable(setReturn, dwGDKEY);
                return setReturn;
            }
            #endregion
            try
            {
                #region Get CreateByQueryCurrent GoodsMasterKeyRelation
                dwQueryCond = setQueryCond.GoodsMasterKeyRelationQueryCond.NewRow();
                dwQueryCond["QUERYTYPE"] = "CreateByQuery";
                dwQueryCond["CONDTYPE"] = "IX_GoodsMasterKeyRelation_Key";
                dwQueryCond["SM"] = dwGDKEY["SM"];
                dwQueryCond["KREAL"] = TargetTable;
                dwQueryCond["KEYDEFTYPE"] = dwGDKEY["KEYDEFTYPE"];
                dwQueryCond["GTPRE"] = dwGDKEY["GTPRE"];
                dwQueryCond["GTKEY"] = dwGDKEY["GTKEY"];
                dwQueryCond["GDKEY"] = dwGDKEY["GDKEY"];
                dwQueryCond["MGDKEY"] = dwGDKEY["GDKEY"];
                #endregion
                setTemp1 = new DataSet();
                setTemp1 = QueryAndCreateTable(dwQueryCond, true, false);
                tableGoodsMasterKeyRelation = setTemp1.Tables["GoodsMasterKeyRelation"];
                if (tableGoodsMasterKeyRelation.Rows.Count == 0)
                {
                    Tracer.Info(logRoute, "Please check GTPREDefRelation defination for the GTPREdef" + dwGDKEY["GTKEY"].ToString().Trim());
                    return setReturn;
                }
                rowGoodsMasterKeyRelation = tableGoodsMasterKeyRelation.Rows[0];
                tableGTPREDefRelation = setTemp1.Tables["GTPREDefRelation"];
                rowGTPREDefRelation = tableGTPREDefRelation.Rows[0];
                #region  if (SMultiKey == "YES")
                if (tableGTPREDefRelation != null)
                {
                    SMultiKey = rowGTPREDefRelation["SMULTIKEY"].ToString().Trim();
                    if (SMultiKey == "YES")
                    {
                        GDKEY = dwGDKEY["GDKEY"].ToString().Trim();
                        #region MGDKEY
                        MKREAL = rowGoodsMasterKeyRelation["MKREAL"].ToString().Trim();
                        #endregion
                        #region SGDKEY
                        SForeignKey = rowGTPREDefRelation["SFOREIGNKEY"].ToString().Trim();
                        SKREAL = rowGoodsMasterKeyRelation["SKREAL"].ToString().Trim();
                        #endregion

                        #region Find the group basetable in order to expore
                        expression = "TBNAME='" + SKREAL + "' and TARGETTABLE='" + MKREAL + "' and Type='JustMap'";
                        dwForeignKeyLists = TBForeignKeyList.Select(expression);
                        if (dwForeignKeyLists.Count() > 0)
                        {
                            dwForeignKeyList = dwForeignKeyLists[0];
                            listKeyGo = GetSourceForeingKey(null, null, dwForeignKeyList);
                            listKeyCome = GetTargetForeingKey(null, null, dwForeignKeyList);
                        }
                        rowReference = setReference.Tables[MKREAL].Rows[0];
                        rowTemp = setGlobal.Tables[SKREAL + "QueryCond"].NewRow();
                        rowTemp["QUERYTYPE"] = "QueryOnly";
                        rowTemp["CONDTYPE"] = SForeignKey;
                        for (int i = 0; i < listKeyCome.Count; i++)
                        {
                            rowTemp[listKeyGo[i].ToString()] = rowReference[listKeyCome[i].ToString()];
                        }
                        setTemp1 = new DataSet();
                        setTemp1 = QueryAndCreateTable(rowTemp);
                        tableExpand = setTemp1.Tables[SKREAL];
                        #endregion
                    }
                    else
                    {
                        setReturn = ImportDataTable(setReturn, dwGDKEY);
                        setReturn.Merge(setTemp1);
                    }
                }
                #endregion

                #region Expand GoodsMasterKeyRelation
                DataSet setExpand = new DataSet();
                DataRow rowRelationExpand = null;
                DataRow rowMasterExpand = null;
                string nametableExpand;
                if (tableExpand != null)
                {
                    int PostionI = 0;
                    nametableExpand = tableExpand.TableName;
                    expression = "TBNAME='" + TargetTable + "' and TARGETTABLE='" + nametableExpand + "' and TYPE='MapMultiKey'";
                    dwForeignKeyLists = TBForeignKeyList.Select(expression);
                    listKeyCome = new List<string>();
                    listKeyGo = new List<string>();
                    if (dwForeignKeyLists.Count() > 0)
                    {
                        dwForeignKeyList = dwForeignKeyLists[0];
                        listKeyGo = GetSourceForeingKey(null, null, dwForeignKeyList);
                        listKeyCome = GetTargetForeingKey(null, null, dwForeignKeyList);
                    }

                    expression = "TBNAME='" + nametableExpand + "' and FOREIGNKEY='PK_" + nametableExpand + "' and TYPE='PrimaryKey'";
                    dwForeignKeyLists = TBForeignKeyList.Select(expression);
                    if (dwForeignKeyLists.Count() > 0)
                    {
                        dwForeignKeyList = dwForeignKeyLists[0];
                        listKeyGDKEY = GetAbsoluteGDKEY(null, null, dwForeignKeyList);
                    }
                    string tempGDKEY = "";
                    foreach (DataRow dwTemp in tableExpand.Rows)
                    {
                        tempGDKEY = "";
                        rowRelationExpand = setGlobal.GoodsMasterKeyRelation.NewRow();
                        rowRelationExpand.ItemArray = rowGoodsMasterKeyRelation.ItemArray;
                        for (int i = 0; i < listKeyGDKEY.Count; i++)
                        {
                            tempGDKEY += dwTemp[listKeyGDKEY[i].ToString()].ToString().Trim() + ".";
                        }
                        tempGDKEY += "***";
                        tempGDKEY = tempGDKEY.Replace(".***", "");
                        rowRelationExpand["SGDKEY"] = tempGDKEY;
                        rowRelationExpand["GDKEY"] = rowRelationExpand["MGDKEY"].ToString().Trim() + "."
                            + rowRelationExpand["SGDKEY"].ToString().Trim();
                        rowMasterExpand = setGlobal.Tables[TargetTable].NewRow();
                        rowMasterExpand.ItemArray = dwGDKEY.ItemArray;
                        #region MapTheKey
                        for (int i = 0; i < listKeyCome.Count; i++)
                        {
                            rowMasterExpand[listKeyGo[i].ToString()] = dwTemp[listKeyCome[i].ToString()];
                        }
                        #endregion
                        rowMasterExpand["GDKEY"] = rowRelationExpand["GDKEY"];
                        rowMasterExpand["SUBSTATUS"] = "NewGoodsMasterKeyRelationComplete;";
                        PostionI = System.Convert.ToInt16(dwTemp["POS"].ToString());
                        rowMasterExpand["GDKEYID"] = PostionI;
                        rowRelationExpand["GDKEYID"] = PostionI;
                        rowRelationExpand = Build(rowRelationExpand, PostionI);
                        rowMasterExpand = Build(rowMasterExpand, PostionI);
                        setExpand = ImportDataTable(setExpand, rowMasterExpand);
                        setExpand = ImportDataTable(setExpand, rowRelationExpand);
                    }
                }
                #endregion
                foreach (DataTable dtTmp in setExpand.Tables)
                {
                    setReturn = ImportDataTable(setReturn, dtTmp);
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return setReturn;
        }
        private DataSet AutoMaterialKeyGeneration(DataRow dwGoodsMasterAssemblePoint, DataRow dwGoodsTypeAssemblePointDef)
        {
            #region Variable
            DataRow dwQueryCond;
            string TargetTable, FTargetTable;
            string SubStatus;
            TargetTable = dwGoodsMasterAssemblePoint.Table.TableName.Replace("QueryCond", "");
            SubStatus = dwGoodsMasterAssemblePoint["SUBSTATUS"].ToString().Trim();
            DataSet setRequest = new DataSet();
            DataSet setReturn = new DataSet();
            DataSet setTemp1 = new DataSet();
            DataSet setTemp2 = new DataSet();
            DataSet setTemp3 = new DataSet();
            Queue QFroeignKey = new Queue();
            Queue QSourceKey = new Queue();
            Dictionary<string, object> dicReturn;
            DataTable tableGTPREDefRelation = null;
            DataTable tableExpand = null;
            DataSet setExpandSource = new DataSet();
            DataTable tableGoodsMasterKeyRelation = null;
            DataRow rowMainKey = null, rowGTPREDefRelationQueryCond = null;
            DataRow rowGoodsMasterKeyRelation = null, rowGoodsMasterKeyRelationQueryCond = null;
            List<string> listKeyCome = null;
            List<string> listKeyGo = null;
            string TBName;
            DataRow rowTemp = null;
            int SGroupLevel;
            DataRow rowReference = null;
            DataTable tableSGDKEY = null;
            DataSet setSGDKEY = new DataSet();
            DataRow rowGroupBase = null;
            string nametableExpand;
            bool flgFind = false;
            DataRow[] rowsTemp;
            string expression;
            string sTargetTable, SMultiKey, SGDKEYGeneration, MSM, MGDKEY, MKREAL, MKeyDefType, MGTPRE, MGTKEY,
              SSM, SGDKEY, SKREAL, SKeyDefType, SGTPRE, SGTKEY,
              SM, KREAL, KeyDefType, GTPRE, GTKEY, GDKEY,
              SForeignKey;
            SKREAL = "";
            KREAL = "";
            #endregion

            #region Validate the Record
            if (TargetTable == "GoodsMasterKey"
                 || TargetTable == "GTPREDefRelation"
                 )
                return setReturn;
            dwGoodsMasterAssemblePoint["SGDKEY"] = dwGoodsMasterAssemblePoint["GDKEY"];
            #endregion
            try
            {
                SMultiKey = dwGoodsTypeAssemblePointDef["SMULTIKEY"].ToString().Trim();
                SGDKEYGeneration = dwGoodsTypeAssemblePointDef["SGDKEYGENERATION"].ToString().Trim();
                SForeignKey = dwGoodsTypeAssemblePointDef["SFOREIGNKEY"].ToString().Trim();
                SKREAL = dwGoodsTypeAssemblePointDef["SKREAL"].ToString().Trim();
                if (SMultiKey != "YES")
                {
                    setReturn = ImportDataTable(setReturn, dwGoodsMasterAssemblePoint);
                }
                else
                {
                    expression = "TBNAME='" + SKREAL + "' and TYPE='AutoMaterialKey' and FOREIGNKEY='" + SForeignKey + "'";
                    dwForeignKeyLists = TBForeignKeyList.Select(expression);
                    FTargetTable = dwForeignKeyLists[0]["TARGETTABLE"].ToString().Trim();
                    rowMainKey = null;
                    if (setReference.Tables.Contains(FTargetTable))
                    {
                        if (setReference.Tables[FTargetTable].Rows.Count > 0)
                        {
                            rowMainKey = setReference.Tables[FTargetTable].Rows[0];
                        }
                    }
                    if (rowMainKey == null)
                    {
                        LoadTable4Reference(dwGoodsMasterAssemblePoint, FTargetTable);
                        rowMainKey = setReference.Tables[FTargetTable].Rows[0];
                    }
                    #region 通过GoodsMasterKeyRelation找到满足左键要求的所有内容
                    //AutoMaterialKey 通过这种方式有些多余，似乎仅仅依靠GTPREDefRelation就足够了。多余总比牵强好。
                    dwQueryCond = setGlobal.Tables["GoodsMasterKeyRelationQueryCond"].NewRow();

                    dwQueryCond["QUERYTYPE"] = "QueryOnly";
                    dwQueryCond["CONDTYPE"] = SForeignKey;
                    dwQueryCond["SM"] = dwGoodsMasterAssemblePoint["SM"];

                    dwQueryCond["KREAL"] = dwGoodsMasterAssemblePoint["SKREAL"];
                    dwQueryCond["KEYDEFTYPE"] = dwGoodsMasterAssemblePoint["SKEYDEFTYPE"];
                    dwQueryCond["GTPRE"] = dwGoodsMasterAssemblePoint["SGTPRE"];
                    dwQueryCond["GTKEY"] = dwGoodsMasterAssemblePoint["SGTKEY"];
                    dwQueryCond["GDKEY"] = dwGoodsMasterAssemblePoint["SGDKEY"];

                    dwQueryCond["MKREAL"] = rowMainKey.Table.TableName;
                    dwQueryCond["MKEYDEFTYPE"] = rowMainKey["KEYDEFTYPE"];
                    dwQueryCond["MGTPRE"] = rowMainKey["GTPRE"];
                    dwQueryCond["MGTKEY"] = rowMainKey["GTKEY"];
                    dwQueryCond["MGDKEY"] = rowMainKey["GDKEY"];
                    setTemp1 = new DataSet();
                    setTemp1 = QueryAndCreateTable(dwQueryCond);
                    setSGDKEY = new DataSet();
                    foreach (DataRow dwTemp in setTemp1.Tables["GoodsMasterKeyRelation"].Rows)
                    {
                        rowGoodsMasterKeyRelation = dwTemp;
                        KREAL = dwTemp["KREAL"].ToString().Trim();
                        dwQueryCond = setGlobal.Tables[KREAL + "QueryCond"].NewRow();
                        dwQueryCond["QUERYTYPE"] = "QueryCond";
                        dwQueryCond["CONDTYPE"] = "IX_" + SKREAL;
                        dwQueryCond["SM"] = dwTemp["SM"];
                        dwQueryCond["KEYDEFTYPE"] = dwTemp["KEYDEFTYPE"];
                        dwQueryCond["GTPRE"] = dwTemp["GTPRE"];
                        dwQueryCond["GTKEY"] = dwTemp["GTKEY"];
                        dwQueryCond["GDKEY"] = dwTemp["GDKEY"];
                        setTemp2 = new DataSet();
                        setTemp2 = QueryAndCreateTable(dwQueryCond);
                        setSGDKEY.Merge(setTemp2.Tables[SKREAL]);
                    }
                    #endregion

                    tableExpand = setSGDKEY.Tables[KREAL];
                    #region Expand GoodsMasterKeyRelation
                    DataSet setExpand = new DataSet();
                    DataRow rowAssemblePoint = null;
                    DataRow rowRelationExpand = null;
                    DataRow rowMasterExpand = null;
                    string masterTable = KREAL;
                    string NewGDKEY = "";
                    string GoodsMovementTypeKey = "";
                    if (SGDKEYGeneration == "Auto"
                        && tableExpand != null)
                    {
                        int PostionI = 0;
                        int Line = 1;
                        foreach (DataRow dwExpand in tableExpand.Rows)
                        {
                            PostionI = System.Convert.ToInt16(dwGoodsMasterAssemblePoint["POS"].ToString());
                            GoodsMovementTypeKey = dwGoodsMasterAssemblePoint["GOODSMOVEMENTTYPEKEY"].ToString().Trim();
                            #region NewRecord
                            rowAssemblePoint = setGlobal.GoodsMasterAssemblePoint.NewRow();
                            rowAssemblePoint.ItemArray = dwGoodsMasterAssemblePoint.ItemArray;
                            SKREAL = dwGoodsMasterAssemblePoint["SKREAL"].ToString().Trim();
                            rowAssemblePoint["LINE"] = Line++;
                            rowRelationExpand = setGlobal.Tables["GOODSMASTERKEYRELATION"].NewRow();
                            rowRelationExpand.ItemArray = rowGoodsMasterKeyRelation.ItemArray;

                            rowMasterExpand = setGlobal.Tables[masterTable].NewRow();
                            rowMasterExpand.ItemArray = dwExpand.ItemArray;
                            #endregion
                            #region NewGDKEY
                            MGDKEY = dwGoodsMasterAssemblePoint["GDKEY"].ToString();
                            SGDKEY = dwExpand["GDKEY"].ToString();
                            dwQueryCond = MapDataRow("QueryOnly", "IX_GoodsMasterKeyRelation_Key",
                                "GoodsMasterKeyRelationQueryCond", dwExpand, null, null, true);
                            dwQueryCond["KREAL"] = dwExpand.Table.TableName;
                            dsResult = new DataSet();
                            dsResult = QueryAndCreateTable(dwQueryCond);
                            if (dsResult.Tables.Contains("GoodsMasterKeyRelation")
                                && dsResult.Tables["GoodsMasterKeyRelation"].Rows.Count > 0
                                )
                            {
                                SGDKEY = dsResult.Tables["GoodsMasterKeyRelation"].Rows[0]["SGDKEY"].ToString();
                            }
                            if (GoodsMovementTypeKey == "OUT")
                            {
                                NewGDKEY = MGDKEY;
                            }
                            else
                            {
                                NewGDKEY = MGDKEY + "." + SGDKEY;
                            }
                            if (SForeignKey == "IX_GoodsMasterKeyRelation_Key")
                            {
                                NewGDKEY = MGDKEY;
                            }
                            rowAssemblePoint["SGDKEY"] = NewGDKEY;
                            rowMasterExpand["GDKEY"] = NewGDKEY;
                            rowRelationExpand["GDKEY"] = NewGDKEY;

                            rowRelationExpand["MKREAL"] = dwGoodsMasterAssemblePoint["KREAL"];
                            rowRelationExpand["MKEYDEFTYPE"] = dwGoodsMasterAssemblePoint["KEYDEFTYPE"]; ;
                            rowRelationExpand["MGTPRE"] = dwGoodsMasterAssemblePoint["GTPRE"]; ;
                            rowRelationExpand["MGTKEY"] = dwGoodsMasterAssemblePoint["GTKEY"];
                            rowRelationExpand["MGDKEY"] = MGDKEY;
                            rowRelationExpand["SKREAL"] = masterTable;
                            rowRelationExpand["SGDKEY"] = SGDKEY;
                            rowMasterExpand["SUBSTATUS"] = "NewGoodsMasterKeyRelationComplete;";
                            dwQueryCond = MapDataRow("QueryOnly", "IX_GoodsMasterKeyRelation_MSCombination",
                                "GoodsMasterKeyRelationQueryCond", rowRelationExpand, null, null, true);
                            dsResult = new DataSet();
                            dsResult = QueryAndCreateTable(dwQueryCond);
                            if (dsResult.Tables.Contains("GoodsMasterKeyRelation")
                                && dsResult.Tables["GoodsMasterKeyRelation"].Rows.Count > 0)
                            {
                                rowAssemblePoint["SGDKEY"] = dsResult.Tables["GoodsMasterKeyRelation"].Rows[0]["GDKEY"];
                            }
                            else
                            {
                                if (GoodsMovementTypeKey != "OUT")
                                {
                                    rowRelationExpand = Build(rowRelationExpand, PostionI);
                                    setExpand = ImportDataTable(setExpand, rowRelationExpand);
                                    rowMasterExpand = UpdateLastPOS(rowMasterExpand, dwExpand);
                                    setExpand = ImportDataTable(setExpand, rowMasterExpand);
                                }
                            }

                            #endregion
                            rowAssemblePoint = Build(rowAssemblePoint, PostionI, Line);
                            setExpand = ImportDataTable(setExpand, rowAssemblePoint);
                        }
                    }
                    #endregion
                    setReturn.Merge(setExpand);
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return setReturn;
        }
        private void LoadTable4Reference(DataRow dwReference, string TBName)
        {
            DataRow dwQueryCond = null;
            DataSet setResult;
            bool blFound = false;
            DataRow dwTemp = null;
            try
            {
                string MKREAL = dwReference["KREAL"].ToString().Trim();

                dwQueryCond = setGlobal.Tables["GoodsMasterKeyRelationQueryCond"].NewRow();
                dwQueryCond["QUERYTYPE"] = "QueryOnly";
                dwQueryCond["CONDTYPE"] = "IX_GoodsMasterKeyRelation_Key";
                dwQueryCond["SM"] = dwReference["SM"];
                dwQueryCond["KREAL"] = MKREAL;
                dwQueryCond["KEYDEFTYPE"] = dwReference["KEYDEFTYPE"];
                dwQueryCond["GTPRE"] = dwReference["GTPRE"];
                dwQueryCond["GTKEY"] = dwReference["GTKEY"];
                dwQueryCond["GDKEY"] = dwReference["GDKEY"];

                while (!blFound)
                {
                    setResult = new DataSet();
                    setResult = QueryAndCreateTable(dwQueryCond);
                    if (setResult.Tables.Contains("GoodsMasterKeyRelation"))
                    {
                        if (setResult.Tables["GoodsMasterKeyRelation"].Rows.Count == 0)
                        {
                            break;
                        }
                        else
                        {
                            MKREAL = setResult.Tables["GoodsMasterKeyRelation"].Rows[0]["MKREAL"].ToString().Trim();
                            if (MKREAL == TBName)//一般不是第一层，第一层应当是界面传递过来的。
                            {
                                blFound = true;
                                dwQueryCond = setGlobal.Tables[MKREAL + "QueryCond"].NewRow();
                                dwTemp = setResult.Tables["GoodsMasterKeyRelation"].Rows[0];
                                dwQueryCond["QUERYTYPE"] = "QueryOnly";
                                dwQueryCond["CONDTYPE"] = "IX_" + MKREAL;
                                dwQueryCond["SM"] = dwTemp["SM"];
                                dwQueryCond["KEYDEFTYPE"] = dwTemp["MKEYDEFTYPE"];
                                dwQueryCond["GTPRE"] = dwTemp["MGTPRE"];
                                dwQueryCond["GTKEY"] = dwTemp["MGTKEY"];
                                dwQueryCond["GDKEY"] = dwTemp["MGDKEY"];
                                setResult = new DataSet();
                                setResult = QueryAndCreateTable(dwQueryCond);
                                setReference.Merge(setResult);
                                break;
                            }
                            else
                            {
                                dwTemp = setResult.Tables["GoodsMasterKeyRelation"].Rows[0];
                                dwQueryCond["SM"] = dwTemp["SM"];
                                dwQueryCond["KREAL"] = dwTemp["MKREAL"];
                                dwQueryCond["KEYDEFTYPE"] = dwTemp["MKEYDEFTYPE"];
                                dwQueryCond["GTPRE"] = dwTemp["MGTPRE"];
                                dwQueryCond["GTKEY"] = dwTemp["MGTKEY"];
                                dwQueryCond["GDKEY"] = dwTemp["MGDKEY"];
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private Dictionary<string, object> LoadDataTableByConditions(string TBName, string ForeignKey,
            string SM, string KeyDefType, string GTPRE, string GTKEY, string GDKEY)
        {
            Dictionary<string, object> dicReturn = new Dictionary<string, object>();
            dicReturn.Add("setReturn", null);
            dicReturn.Add("LastTable", null);
            DataSet setReturn = new DataSet();
            DataSet setTemp, setTemp1, setTemp2;
            DataRow dwQueryCond;
            string LastTable = "";

            try
            {
                #region Get GoodsMasterKeyRelation
                dwQueryCond = setGlobal.Tables["GoodsMasterKeyRelationQueryCond"].NewRow();
                dwQueryCond["QUERYTYPE"] = "QueryOnly";
                dwQueryCond["CONDTYPE"] = "IX_GoodsMasterKeyRelation_Key";
                dwQueryCond["SM"] = SM;
                dwQueryCond["KREAL"] = TBName;
                dwQueryCond["KEYDEFTYPE"] = KeyDefType;
                dwQueryCond["GTPRE"] = GTPRE;
                dwQueryCond["GTKEY"] = GTKEY;
                dwQueryCond["GDKEY"] = GDKEY;
                setTemp = new DataSet();
                setTemp = QueryAndCreateTable(dwQueryCond);
                foreach (DataTable dtTemp in setTemp.Tables)
                {
                    setReturn = ImportDataTable(setReturn, dtTemp);
                }
                #endregion

                #region Get GoodsMasterKey
                dwQueryCond = setGlobal.Tables[TBName + "QueryCond"].NewRow();
                dwQueryCond["QUERYTYPE"] = "QueryOnly";
                dwQueryCond["CONDTYPE"] = "IX_" + TBName;
                dwQueryCond["SM"] = SM;
                dwQueryCond["KEYDEFTYPE"] = KeyDefType;
                dwQueryCond["GTPRE"] = GTPRE;
                dwQueryCond["GTKEY"] = GTKEY;
                dwQueryCond["GDKEY"] = GDKEY;
                setTemp = new DataSet();
                setTemp = QueryAndCreateTable(dwQueryCond);
                foreach (DataTable dtTemp in setTemp.Tables)
                {
                    setReturn = ImportDataTable(setReturn, dtTemp);
                }
                #endregion

                #region Get the GoodsMasterKeyRelation record based on this MGDKEY
                //foreach (DataRow dwTemp in setTemp.Tables[TBName].Rows)
                {
                    dwQueryCond = setGlobal.Tables["GoodsMasterKeyRelationQueryCond"].NewRow();
                    dwQueryCond["QUERYTYPE"] = "QueryOnly";
                    dwQueryCond["CONDTYPE"] = "IX_GoodsMasterKeyRelation_MGDKEY";
                    dwQueryCond["SM"] = SM;
                    dwQueryCond["MKREAL"] = TBName;
                    /*dwQueryCond["MKeyDefType"] = dwTemp["KeyDefType"];
                    dwQueryCond["MGTPRE"] = dwTemp["GTPRE"];
                    dwQueryCond["MGTKEY"] = dwTemp["GTKEY"];
                    dwQueryCond["MGDKEY"] = dwTemp["GDKEY"];
                    */
                    dwQueryCond["MKEYDEFTYPE"] = KeyDefType;
                    dwQueryCond["MGTPRE"] = GTPRE;
                    dwQueryCond["MGTKEY"] = GTKEY;
                    dwQueryCond["MGDKEY"] = GDKEY;
                    setTemp1 = new DataSet();
                    setTemp1 = QueryAndCreateTable(dwQueryCond);
                    //setReturn = ImportDataTable(setReturn, setTemp1.Tables["GoodsMasterKeyRelation"]);

                    foreach (DataRow dwTemp1 in setTemp1.Tables["GoodsMasterKeyRelation"].Rows)
                    {
                        LastTable = dwTemp1["KREAL"].ToString().Trim();
                        dwQueryCond = setGlobal.Tables[LastTable + "QueryCond"].NewRow();
                        dwQueryCond["QUERYTYPE"] = "QueryOnly";
                        dwQueryCond["CONDTYPE"] = "IX_" + LastTable;
                        dwQueryCond["SM"] = SM;
                        dwQueryCond["KEYDEFTYPE"] = dwTemp1["KEYDEFTYPE"];
                        dwQueryCond["GTPRE"] = dwTemp1["GTPRE"];
                        dwQueryCond["GTKEY"] = dwTemp1["GTKEY"];
                        dwQueryCond["GDKEY"] = dwTemp1["GDKEY"];
                        setTemp2 = new DataSet();
                        setTemp2 = QueryAndCreateTable(dwQueryCond);
                        setReturn = ImportDataTable(setReturn, setTemp2.Tables[LastTable]);
                    }
                }
                #endregion
                dicReturn["setReturn"] = setReturn;
                dicReturn["LastTable"] = LastTable;
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return dicReturn;
        }
 
    }
}